package com.incar.chuxing.baiduMap.MarkerOverlay;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.utils.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by michaelpi on 2018/4/16.
 */

public class DownLoadImage {
    private int count = 0;

    void downLoadPic(HashMap<String, Integer> picIdMap, IDownLoadImage downLoadImage) {
        count = 0;
        HashMap<String, Bitmap> loadedBitmaps = new HashMap<>();
        ArrayList<String> keyList = new ArrayList<>();
        ArrayList<Integer> valueList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : picIdMap.entrySet()) {
            keyList.add(entry.getKey());
            valueList.add(entry.getValue());
        }
        Logger.d( "图片数" + keyList.size());

        downLoad(keyList, valueList, loadedBitmaps, downLoadImage);
    }


    private void downLoad(ArrayList<String> keyList, ArrayList<Integer> valueList, HashMap<String, Bitmap> loadedBitmaps, IDownLoadImage downLoadImage) {
        Glide.with(MyApplication.getInstance()).load(((MyApplication) MyApplication.getInstance()).getImageUrl() + keyList.get(count).split(",")[0]).asBitmap().error(valueList.get(count)).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                loadedBitmaps.put(keyList.get(count), bitmap);
                if (count == keyList.size() - 1) {
                    Logger.d( "从网络下载Marker图片--下载完全部 " + keyList.get(count));
                    downLoadImage.onDownLoadDone(loadedBitmaps);
                } else {
                    Logger.d( "从网络下载Marker图片--下载完一张 " + keyList.get(count));
                    count++;
                    downLoad(keyList, valueList, loadedBitmaps, downLoadImage);
                }
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                loadedBitmaps.put(keyList.get(count), ((BitmapDrawable) errorDrawable).getBitmap());
                if (count == keyList.size() - 1) {
                    Logger.d( "下载完一个-默认图片--下载完" + keyList.get(count));
                    downLoadImage.onDownLoadDone(loadedBitmaps);
                } else {
                    Logger.d( "下载完一个-默认图片--下载完" + keyList.get(count));
                    count++;
                    downLoad(keyList, valueList, loadedBitmaps, downLoadImage);
                }
            }
        });
    }


    public interface IDownLoadImage {
        void onDownLoadDone(HashMap<String, Bitmap> loadedBitmaps);
    }
}
